// src/components/sponsorDashboard/mainContent/MainContentSection.tsx

import { useState, useEffect, useCallback, useRef } from 'react';
import Headline from '@/components/sponsorDashboard/header/Headline';
import DashboardTabs from '@/components/sponsorDashboard/mainContent/DashboardTabs';
import Table from '@/components/sponsorDashboard/mainContent/Table';
import Pagination from '@/components/sponsorDashboard/mainContent/Pagination';
import Overview from '@/components/sponsorDashboard/mainContent/Overview';
import Filter from '@/components/popups/sponsorTable/sponsorTableFilter/Filter';
import ColumnSelector from '@/components/sponsorDashboard/mainContent/ColumnSelector';
import { fetchSponsorRecords } from '@/services/sponsorDashboardService/tableSponsorRecords';
import type { SponsorRecord } from '@/types/types';
import { useDashboardTabStore } from '@/store/dashboardTabStore';
import { usePermissions } from '@/utils/permissionUtils';

const MainContentSection = () => {
  const { canViewSponsorsDashboardContent } = usePermissions();

  const { currentTab } = useDashboardTabStore();
  const [searchText, setSearchText] = useState('');
  const [sponsors, setSponsors] = useState<SponsorRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [hasSearched, setHasSearched] = useState(false);
  const pageSize = 10;

  const searchTextRef = useRef(searchText);

  useEffect(() => {
    searchTextRef.current = searchText;
  }, [searchText]);

  const allHeaders = [
    { key: "umbrella_code", label: "Umbrella Code" },
    { key: "company_code", label: "Company Code" },
    { key: "company_name", label: "Company Name" },
    { key: "sponsor_id", label: "Company ID" },
    { key: "program_code", label: "Program" },
    { key: "program_id", label: "Program ID" },
    { key: "program_length", label: "Program Length" },
    { key: "coop_program", label: "CO-OP Program" },
    { key: "position", label: "Position" },
    { key: "status", label: "Status" },
    { key: "faculty", label: "Faculty" },
    { key: "program_year", label: "Year" },
    { key: "total_amount_per_position", label: "Total Amount Per Position" },
    { key: "sponsorship_cost", label: "Sponsorship Cost" },
    { key: "logo", label: "Logo" },
    { key: "logo_last_updated", label: "Logo Last Updated" },
  ];

  const tableHeaders = [
    { label: "Umbrella Code", key: "umbrella_code" },
    { label: "Company Code", key: "company_code" },
    {
      label: "Company Name",
      key: "company_name",
      expandable: true,
      expanded: false,
      children: [
        { label: "Company ID", key: "sponsor_id" },
      ],
    },
    {
      label: "Program",
      key: "program_code",
      expandable: true,
      expanded: false,
      children: [
        { label: "Program ID", key: "program_id" },
        { label: "Program Length", key: "program_length" },
      ],
    },
    { label: "CO-OP Program", key: "coop_program" },
    { label: "Position", key: "position" },
    { label: "Status", key: "status" },
    { label: "Faculty", key: "faculty" },
    { label: "Year", key: "program_year" },
    { label: "Total Amount Per Position", key: "total_amount_per_position" },
    { label: "Sponsorship Cost", key: "sponsorship_cost" },
    { label: "Logo", key: "logo" },
    { label: "Logo Last Updated", key: "logo_last_updated" },
  ];

  const childKeys = tableHeaders
    .flatMap(h => h.children || [])
    .map(child => child.key);

  const mainHeaderKeys = allHeaders
    .map(h => h.key)
    .filter(key => !childKeys.includes(key));

  const initialMainKeys = mainHeaderKeys.slice(0, 7);
  const initialChildKeys = tableHeaders
    .filter(h => initialMainKeys.includes(h.key) && h.children)
    .flatMap(h => h.children!.map(child => child.key));

  const [selectedHeaders, setSelectedHeaders] = useState<string[]>([...initialMainKeys, ...initialChildKeys]);
  const [showFilter, setShowFilter] = useState(false);
  const [searchFilters, setSearchFilters] = useState<{
    fromYear: string;
    toYear: string;
    selectedPrograms: string[];
    selectedFaculties: string[];
    selectedCoopPrograms: string[];
    selectedStatus: string;
  }>({
    fromYear: '',
    toYear: '',
    selectedPrograms: [],
    selectedFaculties: [],
    selectedCoopPrograms: [],
    selectedStatus: 'All'
  });

  const loadInitialData = useCallback(async (page: number) => {
    try {
      setLoading(true);
      const response = await fetchSponsorRecords({
        year_from: parseInt(searchFilters.fromYear) || 20,
        year_to: parseInt(searchFilters.toYear) || 2099,
        program_code: Array.isArray(searchFilters.selectedPrograms) && searchFilters.selectedPrograms.length > 0 ? searchFilters.selectedPrograms : undefined,
        faculty: Array.isArray(searchFilters.selectedFaculties) && searchFilters.selectedFaculties.length > 0 ? searchFilters.selectedFaculties : undefined,
        coop_program: Array.isArray(searchFilters.selectedCoopPrograms) && searchFilters.selectedCoopPrograms.length > 0 ? searchFilters.selectedCoopPrograms : undefined,
        current:
          searchFilters.selectedStatus === 'Current'
            ? true
            : searchFilters.selectedStatus === 'Not Current'
              ? false
              : undefined,
        keyword: undefined,
        page,
        page_size: pageSize,
      });
      setTimeout(() => {
        setSponsors(response.items || []);
        setTotalCount(response.meta?.total || 0);
        setLoading(false);
      }, 200);
    } catch (err) {
      console.error('Failed to fetch sponsor records:', err);
      setLoading(false);
    }
  }, [searchFilters, pageSize]);

  const loadSearchData = useCallback(async (page: number, keyword: string) => {
    try {
      setLoading(true);
      const response = await fetchSponsorRecords({
        year_from: parseInt(searchFilters.fromYear) || 20,
        year_to: parseInt(searchFilters.toYear) || 2099,
        program_code: Array.isArray(searchFilters.selectedPrograms) && searchFilters.selectedPrograms.length > 0 ? searchFilters.selectedPrograms : undefined,
        faculty: Array.isArray(searchFilters.selectedFaculties) && searchFilters.selectedFaculties.length > 0 ? searchFilters.selectedFaculties : undefined,
        coop_program: Array.isArray(searchFilters.selectedCoopPrograms) && searchFilters.selectedCoopPrograms.length > 0 ? searchFilters.selectedCoopPrograms : undefined,
        current:
          searchFilters.selectedStatus === 'Current'
            ? true
            : searchFilters.selectedStatus === 'Not Current'
              ? false
              : undefined,
        keyword: keyword || undefined,
        page,
        page_size: pageSize,
      });
      setTimeout(() => {
        setSponsors(response.items || []);
        setTotalCount(response.meta?.total || 0);
        setLoading(false);
      }, 200);
    } catch (err) {
      console.error('Failed to fetch sponsor records:', err);
      setLoading(false);
    }
  }, [searchFilters, pageSize]);

  useEffect(() => {
    loadInitialData(1);
  }, [loadInitialData]);

  useEffect(() => {
    if (hasSearched && searchTextRef.current.trim()) {
      loadSearchData(currentPage, searchTextRef.current.trim());
    } else {
      loadInitialData(currentPage);
    }
  }, [currentPage, hasSearched, loadSearchData, loadInitialData]);

  const handleSearchClick = () => {
    setHasSearched(true);
    setCurrentPage(1);
    loadSearchData(1, searchTextRef.current.trim());
  };

  const handleFilter = (filters: typeof searchFilters) => {
    setSearchFilters(filters);
    setHasSearched(false);
    setCurrentPage(1);
    loadInitialData(1);
    setShowFilter(false);
  };

  const handleUpdateSelectedHeaders = (keys: string[]) => {
    setSelectedHeaders(keys);
  };

  const handleDownloadTableData = async () => {
    if (downloading) return;
    
    setDownloading(true);
    try {
      let allItems: SponsorRecord[] = [];
      let currentPage = 1;
      const pageSize = 100;
      let hasMoreData = true;

      while (hasMoreData) {
        const response = await fetchSponsorRecords({
          year_from: searchFilters.fromYear ? parseInt(searchFilters.fromYear) : 2000,
          year_to: searchFilters.toYear ? parseInt(searchFilters.toYear) : 2030,
          page: currentPage,
          page_size: pageSize,
          program_code: searchFilters.selectedPrograms.length > 0 ? searchFilters.selectedPrograms : undefined,
          faculty: searchFilters.selectedFaculties.length > 0 ? searchFilters.selectedFaculties : undefined,
          coop_program: searchFilters.selectedCoopPrograms.length > 0 ? searchFilters.selectedCoopPrograms : undefined,
          current: searchFilters.selectedStatus === 'Current' ? true : 
                  searchFilters.selectedStatus === 'Not Current' ? false : undefined,
          keyword: searchText.trim() || undefined,
        });

        if (response.items && response.items.length > 0) {
          allItems = [...allItems, ...response.items];
          
          if (response.items.length < pageSize || allItems.length >= (response.meta?.total || 0)) {
            hasMoreData = false;
          } else {
            currentPage++;
          }
        } else {
          hasMoreData = false;
        }
      }

      if (allItems.length > 0) {
        const headers = selectedHeaders.map(key => {
          const header = allHeaders.find(h => h.key === key);
          return header ? header.label : key;
        });

        const rows = allItems.map(sponsor => 
          selectedHeaders.map(key => {
            const value = sponsor[key as keyof SponsorRecord];
            if (value !== null && value !== undefined) {
              if (typeof value === 'boolean') {
                return value ? 'Yes' : 'No';
              }
              return String(value);
            }
            return '';
          })
        );

        const csvContent = [
          headers.join(','),
          ...rows.map(row => row.map(cell => `"${cell.replace(/"/g, '""')}"`).join(','))
        ].join('\n');

        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', `sponsor_table_data_${new Date().toISOString().split('T')[0]}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
      }
    } catch (error) {
      console.error('Download failed:', error);
    } finally {
      setDownloading(false);
    }
  };

  if (!canViewSponsorsDashboardContent) {
    return (
      <div className="flex-1 p-6 bg-gray-50 dark:bg-slate-900">
        <Headline 
          onDownload={handleDownloadTableData}
          downloading={downloading}
          hasData={sponsors.length > 0}
        />
        <div className="mt-6 bg-white dark:bg-slate-800 rounded-lg shadow-sm border border-gray-200 dark:border-slate-700 p-8">
          <div className="text-center">
            <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 dark:bg-red-900">
              <svg className="h-6 w-6 text-red-600 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <h3 className="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">
              Access Denied
            </h3>
            <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
              You do not have permission to view the Sponsors Dashboard content.
              Please contact your administrator.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <section className="flex-1 bg-white dark:bg-slate-900 overflow-y-auto font-poppins py-3 sm:py-6 transition-all duration-300">
      <Headline 
        onDownload={handleDownloadTableData}
        downloading={downloading}
        hasData={sponsors.length > 0}
      />
      <div className="bg-white dark:bg-slate-800 mx-4 sm:mx-8 md:mx-12 my-6 sm:my-10 rounded-3xl shadow-xl border border-gray-200 dark:border-slate-700 overflow-hidden">
        <div className="px-4 sm:px-6 md:px-8 lg:px-10 py-4 sm:py-6 md:py-8 gap-3 sm:gap-4">
          <DashboardTabs
            onFilterClick={() => setShowFilter(true)}
            searchText={searchText}
            setSearchText={setSearchText}
            onSearchClick={handleSearchClick}
          />
          {currentTab === 'table' && (
            <>
              <ColumnSelector
                allHeaders={allHeaders}
                selectedHeaders={selectedHeaders}
                updateSelectedHeaders={handleUpdateSelectedHeaders}
              />
              {loading ? (
                <div className="text-center py-64 text-gray-500 dark:text-gray-400 text-lg animate-pulse">
                  <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 dark:border-cyan-400 mb-4"></div>
                  <div>Loading sponsor records...</div>
                </div>
              ) : sponsors.length === 0 ? (
                <div className="flex flex-col items-center justify-center w-full py-56 text-gray-400 dark:text-gray-500">
                  <span className="text-6xl mb-6 text-blue-200 dark:text-cyan-900">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-16 h-16 mx-auto">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-3A2.25 2.25 0 008.25 5.25V9m10.5 0v10.125c0 1.012-.838 1.875-1.875 1.875H7.125A1.875 1.875 0 015.25 19.125V9m13.5 0H5.25m13.5 0a2.25 2.25 0 012.25 2.25v7.125A2.25 2.25 0 0118.75 20.25H5.25A2.25 2.25 0 013 18.375V11.25A2.25 2.25 0 015.25 9h13.5z" />
                    </svg>
                  </span>
                  <span className="italic text-sm sm:text-base md:text-lg text-center mb-6">
                    No sponsor records found.
                  </span>
                  <button
                    className="px-6 py-3 bg-blue-600 dark:bg-cyan-700 text-white rounded-xl hover:bg-blue-700 dark:hover:bg-cyan-800 hover:shadow-lg transition-all duration-200 font-medium"
                    onClick={() => {
                      window.location.reload();
                    }}
                  >
                    Refresh Data
                  </button>
                </div>
              ) : (
                <Table
                  sponsors={sponsors}
                  selectedHeaders={selectedHeaders}
                />
              )}
              <Pagination
                currentPage={currentPage}
                setCurrentPage={setCurrentPage}
                totalCount={totalCount}
                pageSize={pageSize}
              />
            </>
          )}
          {currentTab === 'overview' && <Overview />}
        </div>
      </div>
      {showFilter && (
        <Filter
          onClose={() => setShowFilter(false)}
          onApply={handleFilter}
        />
      )}
    </section>
  );
};

export default MainContentSection;